# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date:
# @Last Modified by: CPS
# @Last Modified time: 2021-04-12 03:25:48.660601
# @file_path "D:\CPS\IDE\JS_SublmieText\Data\Packages\CPS"
# @Filename "main.py"
# @Description: 功能描述
#


import sublime
import sublime_plugin
import os
from imp import reload


if int(sublime.version()) < 3176:
    raise ImportWarning("本插件不支持当前版本，请使用大于等于3176的sublime Text")


from .core import utils
from .core import beautify

PLUGIN_NAME = "testt_syntax_beautify"
SETTING_FILE = "testt.sublime-settings"
SETTINGS = {}

def get_floder_list() -> dict:
    return {
        'user_path':os.path.join(sublime.packages_path(),'User'),
        'default_settings':os.path.join(sublime.packages_path(), PLUGIN_NAME, '.sublime', SETTING_FILE),
        'user_settings':os.path.join(sublime.packages_path(),'User', SETTING_FILE),
    }

def plugin_loaded():
    print(f'{PLUGIN_NAME} 加载成功')
    def plugin_loaded_async():
        global SETTINGS
        global FOLDER_LIST

        FOLDER_LIST = get_floder_list()

        with open(FOLDER_LIST['default_settings'], 'r', encoding='utf8') as f:
            SETTINGS = sublime.decode_value(f.read()).get(PLUGIN_NAME, {})
            if len(list(SETTINGS.keys())) == 0:
                raise Exception('读取配置失败 ~~~ 请确保一下文件真实存在： ',FOLDER_LIST['default_settings'])
            # print('读取settings 1: ', SETTINGS.keys())

        user_settings = sublime.load_settings(SETTING_FILE)
        utils.recursive_update(SETTINGS, user_settings.to_dict()[PLUGIN_NAME])
        user_settings.add_on_change(SETTING_FILE, _on_settings_change)

    def _on_settings_change(key:str=None) -> dict:
        global SETTINGS
        
        tmp = sublime.load_settings(SETTING_FILE).get(PLUGIN_NAME, False)

        if not tmp or not isinstance(tmp, dict): return

        utils.recursive_update(SETTINGS, tmp)

        print(f'{SETTING_FILE} 触发更新。')
        return SETTINGS
        
    # 在另一个进程执行该函数( 这样不会阻塞窗口的初始化，造成载入文件卡顿 )
    sublime.set_timeout_async(plugin_loaded_async)




# 常用声明周期钩子
class ExecEventListener(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        global SETTINGS
        if SETTINGS.get('format_on_save'):
            sublime.active_window().run_command('testt_beautify_currt_file')


# 默认快捷键 ["alt+t"]
class TesttSyntaxBeautifyReloadCommand(sublime_plugin.TextCommand):
    def run(self, edit) -> None:
        print(f'重新加载 {PLUGIN_NAME}')
        reload(beautify)


# 格式化当前文件[支持格式： vue/js/ts/pug/stylus/css]
class TesttBeautifyCurrtFileCommand(sublime_plugin.TextCommand):
    def run(self, edit, syntax=None):
        # 异步格式化文件，不卡主程序执行
        sublime.set_timeout_async(self.beautify(edit,syntax), 0)

    def beautify(self, edit, syntax=None) -> None:
        _settings = SETTINGS.get('global', {})

        # 当前文件内容转换成字符串
        region = sublime.Region(0, self.view.size())
        buffer_str = self.view.substr(region)

        # 获取当前文件语法
        if not syntax:
            print("self.view.settings().get('syntax'): ", self.view.settings().get('syntax'))
            syntax = utils.check_stynax(self.view.file_name()) or utils.check_stynax(self.view.settings().get('syntax'))

        if not syntax: 
            return print('无法识别当前语法： ')

        if syntax in ['python']:
            return print('不支持当前文件语法解析： ', syntax)

        # 获取当前鼠标位置
        cursor_offset = self.view.sel()[0].a

        # 获取当前语法配置
        # options = _settings.get(syntax, {})
        options = utils.recursive_update(_settings, _settings.get(syntax, {}))

        # 传送数据
        # print('当前语法： ', options.keys())
        res = beautify.beautifyStr(buffer_str, syntax, cursor_offset, options)
        
        if res and isinstance(res, dict) and 'formatted' in res:
            # 替换新数据到当前文件
            self.view.replace(edit, region, res['formatted'])
            if _settings.get("show_view_at_center_when_format", False) :
                self.view.show_at_center(res['cursorOffset'])

            if int(res['cursorOffset']) > 0: 
                sublime.Region((res['cursorOffset'],res['cursorOffset']))

            print('格式化成功:', syntax)

        else:
            print('格式化失败： ', res)

# 已选内容的格式化
class TesttBeautifySelectRegionCommand(sublime_plugin.TextCommand):
    def run(self, edit, syntax=None):

        # 检测选区
        if self.view.sel()[0].empty() : return print('当前没有任何文件')

        # 检测语法是否支持
        if not syntax : return False

        # 当前文件第一个选区
        region = self.view.sel()[0]
        buffer_str = self.view.substr(region)

        # 获取当前鼠标位置
        cursor_offset = self.view.sel()[0].a

        # 获取当前配置
        options = SETTINGS.get(syntax, {})

        # 先格式化
        res = beautify.beautifyStr(buffer_str, syntax, cursor_offset, options)

        # 如果时html转换pug，
        if syntax == 'html2pug':
            syntax = 'pug'
            options = SETTINGS.get(syntax, {})
            res = beautify.beautifyStr(res['formatted'], syntax, cursor_offset, options)

        # 格式化成功
        if res and 'formatted' in res:
            # 替换新数据到当前文件
            self.view.replace(edit, region, res['formatted'])
            self.view.show_at_center(res['cursorOffset'])

            if int(res['cursorOffset']) > 0: sublime.Region((res['cursorOffset'],res['cursorOffset']))
            print('格式化成功:',os.path.basename(self.view.file_name()))
